package com.jk.vehicle.core.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.jk.vehicle.core.constants.TokenConstants;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

/**
 * token 生成、验证、解码
 *
 * @author wuzhipeng
 */
public class TokenUtil {

    /**
     * 根据参数生成token
     *
     * @param payloads 参数内容
     * @return
     */
    public static String genToken(Map<String, String> payloads) throws UnsupportedEncodingException {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("alg", "HS256");
        map.put("typ", "JWT");
        JWTCreator.Builder jwtBuilder = JWT.create().withHeader(map); // header
        for (Map.Entry<String, String> entry : payloads.entrySet()) {
            jwtBuilder.withClaim(entry.getKey(), entry.getValue());
        }
        return jwtBuilder.sign(Algorithm.HMAC256(TokenConstants.SECRET));
    }

    /**
     * token验证
     *
     * @param token
     * @return
     * @throws Exception
     */
    public static Map<String, Claim> verifyToken(String token) throws Exception {
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(TokenConstants.SECRET)).build();
        DecodedJWT jwt = verifier.verify(token);
        Map<String, Claim> claims = jwt.getClaims();
        return claims;
    }
}
